<template>
  <!-- 添加  搜所 -->
  <div class="app-container">
    <div>
      <el-col align="left" :span="3"> 单编号:{{ inventory_numbering }} </el-col>
      制单人: admin
    </div>

    <div class="filter-container">
      <el-row>
        <el-col align="right" :span="23">
          <el-col align="right" :span="4.5">
            供应商:
            <el-select v-model="formItem_select" placeholder="请选择供应商">
              <el-option
                v-for="item in supplier_list"
                :key="item.sid"
                :label="item.supplierName"
                :value="item.sid"
              >
              </el-option>
            </el-select>
          </el-col>

          <el-button
            type="primary add_btn height32"
            size="small"
            @click="Go_inventory()"
            >直接入库</el-button
          >
          <el-button
            type="primary add_btn height32"
            size="small"
            @click="submit_inventory()"
            >提交审核</el-button
          >
        </el-col>
      </el-row>
    </div>

    <div class="filter-container">
      <el-row>
        <el-col align="right" :span="23">
          <el-button
            type="primary add_btn height32"
            icon="el-icon-circle-plus-outline"
            size="small"
            @click="handleCreatebutton"
          >
            新增
          </el-button>

          <el-button
            type="success add_btn height32"
            icon="el-icon-circle-plus-outline"
            size="small"
            @click="Volume_set"
          >
            批量设置
          </el-button>

          <el-button
            type="info add_btn height32"
            size="small"
            @click="Numerical_empty"
          >
            清空数值
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表 -->
    <el-table :data="list">
      <el-table-column label="Id" prop="purchaseId" align="center">
      </el-table-column>
      <!--  药品名称id medicinesId -->
      <el-table-column label="药品名称" prop="medicinesName" align="center" />
      <!-- <el-table-column
        label="批次库存ID"
        prop="batchesOfInventoryId"
        align="center"
      /> -->
      <el-table-column label="采购数量" prop="purchaseNum" align="center" />
      <el-table-column label="采购单位" prop="purchaseUnit" align="center" />
      <el-table-column
        label="批发价"
        prop="purchaseTradePrice"
        align="center"
      />
      <el-table-column
        label="处方佳"
        prop="purchasePrescriptionPrice"
        align="center"
      />
      <el-table-column
        label="采购批发总额"
        prop="purchaseTradeTotalAmount"
        align="center"
      />
      <el-table-column
        label="采购处方总额"
        prop="purchasePrescriptionTotalAmount"
        align="center"
      />
      <el-table-column label="创建时间" prop="createTime" align="center" />

      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handleUpdate(scope.row)"
          ></el-button>
        </template>
      </el-table-column>

      <el-table-column align="left">
        <template slot-scope="scope">
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDelete(scope.$index, scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页栏 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[8, 10, 25, 50]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 新增 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="125px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item
          label="药品ID"
          prop="medicinesId"
          placeholder="请选择填写医院药品ID"
          size="small"
        >
          <el-input
            v-model="temp.medicinesId"
            @click.native="Drug_model = true"
          />
        </el-form-item>

        <el-form-item
          label="批次库存ID"
          prop="batchesOfInventoryId"
          placeholder="请选择填写批次库存ID"
          size="small"
          hidden
        >
          <el-input v-model="temp.batchesOfInventoryId" />
        </el-form-item>

        <el-form-item
          label="采购数量"
          prop="purchaseNum"
          placeholder="请选择填写采购数量"
          size="small"
        >
          <el-input v-model="temp.purchaseNum" />
        </el-form-item>

        <el-form-item
          label="采购单位"
          prop="purchaseUnit"
          placeholder="请选择填写采购单位"
          size="small"
        >
          <el-input v-model="temp.purchaseUnit" />
        </el-form-item>

        <el-form-item
          label="批发价"
          prop="purchaseTradePrice"
          placeholder="请选择填写批发价"
          size="small"
        >
          <el-input v-model="temp.purchaseTradePrice" />
        </el-form-item>

        <el-form-item
          label="处方价"
          prop="purchasePrescriptionPrice"
          placeholder="请选择填写处方价"
          size="small"
        >
          <el-input v-model="temp.purchasePrescriptionPrice" />
        </el-form-item>

        <el-form-item
          label="采购批发总额"
          prop="purchaseTradeTotalAmount"
          placeholder="请选择填写采购批发总额"
          size="small"
        >
          <el-input v-model="temp.purchaseTradeTotalAmount" />
        </el-form-item>

        <el-form-item
          label="采购处方总额"
          prop="purchasePrescriptionTotalAmount"
          placeholder="请选择填写采购处方总额"
          size="small"
        >
          <el-input v-model="temp.purchasePrescriptionTotalAmount" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="small"
          @click="dialogStatus === insertData()"
        >
          保存
        </el-button>
        <el-button size="small" @click="dialogFormVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 修改弹出框 -->
    <el-dialog
      :title="textMap2[dialogStatus2]"
      :visible.sync="dialogFormVisible2"
    >
      <el-form
        ref="update_from"
        :rules="rules"
        :model="update_temp"
        label-position="left"
        label-width="125px"
        style="width: 400px; margin-left: 50px"
      >
        <h3 align="center" id="update_name">
          药品名称 :{{ medicinesName }} 原处方价 :{{
            purchasePrescriptionPrice
          }}
          原批发价 :{{ purchaseTradePrice }}
        </h3>

        <br />
        <el-form-item
          label="采购数量"
          prop="purchaseNum"
          placeholder="请修改采购数量"
          size="small"
        >
          <el-input v-model="update_temp.purchaseNum" />
        </el-form-item>

        <el-form-item
          label="处方价"
          prop="purchasePrescriptionPrice"
          placeholder="请修改处方价"
          size="small"
        >
          <el-input v-model="update_temp.purchasePrescriptionPrice" />
        </el-form-item>

        <el-form-item
          label="批发价"
          prop="purchaseTradePrice"
          placeholder="请修改批发价"
          size="small"
        >
          <el-input v-model="update_temp.purchaseTradePrice" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="small"
          @click="dialogStatus2 === updateData()"
        >
          保存
        </el-button>
        <el-button size="small" @click="dialogFormVisible2 = false">
          关闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加药品模态框 -->
    <el-dialog :visible.sync="Drug_model" width="83%">
      <div><h2 align="center">添加药品</h2></div>
      <div>
        <el-table :data="drug_query">
          <!-- <el-table-column label="Id" prop="medicinesId" align="center" /> -->

          <el-table-column
            label="药品编号"
            prop="medicinesNumber"
            align="center"
          />
          <el-table-column
            label="药品名称"
            prop="medicinesName"
            align="center"
          />
          <el-table-column
            label="药品分类"
            prop="medicinesClass"
            align="center"
          />
          <el-table-column
            label="处方类型"
            prop="prescriptionType"
            align="center"
          />
          <el-table-column label="单位（g/条）" prop="unit" align="center" />
          <el-table-column label="换算量" prop="conversion" align="center" />
          <el-table-column label="关键字" prop="keywords" align="center" />
          <el-table-column label="生产厂家" prop="producter" align="center" />

          <el-table-column label="选择" prop="" align="center">
            <template slot-scope="scope">
              <i
                style="margin: 0 10px; cursor: pointer"
                @click="clickItemInfo(scope.row)"
                class="el-icon-search"
              ></i>
            </template>
          </el-table-column>
        </el-table></div
    ></el-dialog>

    <!-- 添加批次库存ID模态框 -->
  </div>
</template>


<script>
import { DzmHisPurchase_list } from "@/api/api_g";
import { DzmHisMember_list } from "@/api/api_g"; //查询——药品
// import { DzmHisPurchase_batch_query } from "@/api/api_g"; //查询—批量
import { DzmHisPurchase_insert } from "@/api/api_g";
import { DzmHisPurchase_update } from "@/api/api_g";
import { DzmHisPurchase_update_getid } from "@/api/api_g";
import { DzmHisPurchase_delete } from "@/api/api_g";
import { DzmHisSupplier_list } from "@/api/api_g"; //供应商id
import { DzmHisBatchesOfInventory_insert } from "@/api/api_g"; //供应商id
import { dzmHisPurchase_update_state } from "@/api/api_g"; //供应商id

export default {
  name: "doctor",
  data() {
    const tId = this.$route.query.dictId;
    return {
      // 分页后的当前页数据
      list: [],
      //当前数据页的第几页
      currentPage: 1,
      // 总数据条数xx
      total: 0,
      // 每页显示多少行数据,默认为10条
      pagesize: 8,
      // 代表是从后端获取的所有数据
      ticket: [],
      // 控制编辑排版信息对话框
      open: false,

      monitorForm: {},

      // 表单参数
      // temp: "",
      //update 表单
      update_temp: "",

      // 重置 添加表单
      resetTemp() {
        this.temp = {};
      },
      // 重置修改表单
      update_resetTemp() {
        this.update_temp = {};
      },
      temp: {
        // 新增
        medicinesId: "",
        batchesOfInventoryId: "",
        purchaseNum: "",
        purchaseUnit: "",
        purchaseTradePrice: "",
        purchasePrescriptionPrice: "",
        purchaseTradeTotalAmount: "",
        purchasePrescriptionTotalAmount: "",
        createTime: "",
      },
      dialogFormVisible: false, //新增修改弹出框
      dialogStatus: "", //弹出框 显示隐藏控制
      textMap: {
        create: "新增",
      },

      update_temp: {
        // 新增/修改temp
        medicinesId: "",
        purchaseNum: "",
        purchaseTradePrice: "",
        purchasePrescriptionPrice: "",
      },
      dialogFormVisible2: false,
      dialogStatus2: "", //弹出框 显示隐藏控制
      textMap2: {
        create: "修改",
      },

      rules: {
        //新增修改保存时 校验规则
        // medicinesId: [
        //   { required: true, message: "医院药品不能为空", trigger: "blur" },
        // ],
        // batchesOfInventoryId: [
        //   { required: true, message: "批次库存ID不能为空", trigger: "blur" },
        // ],
        purchaseNum: [
          { required: true, message: "采购数量不能为空", trigger: "blur" },
        ],
        purchaseUnit: [
          { required: true, message: "采购单位不能为空", trigger: "blur" },
        ],
        purchaseTradePrice: [
          { required: true, message: "批发价不能为空", trigger: "blur" },
        ],
        purchasePrescriptionPrice: [
          { required: true, message: "处方价不能为空", trigger: "blur" },
        ],
        purchaseTradeTotalAmount: [
          { required: true, message: "采购批发总额不能为空", trigger: "blur" },
        ],

        purchasePrescriptionTotalAmount: [
          { required: true, message: "采购处方总额不能为空", trigger: "blur" },
        ],
      },
      //添加 —— 医院药品模态框
      Drug_model: false,
      drug_query: [],

      //添加 —— 批次库存ID模态框
      // Drug_model_batId: false,
      // batch_query: [],
      //update ————回显的行
      purchasePrescriptionPrice: "",
      purchaseTradePrice: "",
      medicinesName: "",

      //采购单编号
      inventory_numbering: "",

      //提交审核
      submit_audit: {
        batchesOfInventoryId: "", //	批次库存ID
        // company_id: "", //	诊所ID
        supplierId: "", //	供应商ID
        batchesOfInventoryNumber: "", //	采购单编号
        // purchasing_agent_id: "", //	采购员ID
        batchesOfInventoryTotalMoney: "", //采购总金额
        batchesOfInventoryDate: "", //	制单日期
        batches_of_inventory_status: "", //	审核标记；未审核：1，已审核：2
        batches_of_inventory_verifier: "", //	审核人员ID
        batches_of_inventory_verifier_date: "", //	审核日期
      },

      supplier_list: "",
      formItem_select: "",
    };
  },
  mounted() {
    this.getDoctors();
    this.drug_module_query();
    this.supplier();
    this.inventory_numbering =
      this.getProjectNum() + Math.floor(Math.random() * 100000); // 如果是6位或者8位随机数，相应的 *1000000或者 *100000000就行了
  },
  methods: {
    /** 查询 */
    getDoctors() {
      //this.listLoading = true;
      DzmHisPurchase_list().then((response) => {
        // console.log(response.data[0]);
        if (response.code === 200) {
          this.ticket = response.data;
          //获取返回数据的总行数
          this.total = response.data.length;
          // 获取当前页的数据,此方法在下方定义
          this.getDoctorInfo();
          this.$message({
            message: "数据加载成功",
            type: "success",
          });
        } else {
          // 失败提示信息
          this.$$message({
            message: "数据加载错误",
            type: "error",
          });
        }
      });
    },
    // 此方法用来获取当前页的数据
    getDoctorInfo() {
      // 清空表格的list 数据
      this.list = [];
      // 获取当前页的数据
      for (
        let i = (this.currentPage - 1) * this.pagesize;
        i < this.total;
        i++
      ) {
        // 将便利的数据添加到 list 里面
        this.list.push(this.ticket[i]);
        // 判断是否达到每一页的要求
        if (this.list.length === this.pagesize) break;
      }
    },

    // 分页时修改每页的行数,这里会自动传入一个size
    handleSizeChange(size) {
      // 修改当前每页的数据行数
      this.pagesize = size;
      // 数据重新分页
      this.getDoctorInfo();
    },
    // 调整当前的页码
    handleCurrentChange(pageNumber) {
      // 修改当前的页码
      this.currentPage = pageNumber;
      //数据重新分页
      this.getDoctorInfo();
    },

    async handleDelete(index, rowdata) {
      console.log(rowdata.purchaseId);

      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })

        .then(() => {
          DzmHisPurchase_delete(rowdata.purchaseId).then(() => {
            this.getDoctors();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleCreatebutton() {
      // 点击新增操作
      this.resetTemp(); //表单重置
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    insertData() {
      // 执行后端 新增方法
      this.temp.batchesOfInventoryId = this.inventory_numbering;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          DzmHisPurchase_insert(this.temp).then((res) => {
            if (res.code == 200) {
              this.dialogFormVisible = false;
              this.getDoctors();
              this.$notify({
                title: "新增",
                message: "新增成功!",
                type: "success",
                duration: 2000,
              });
            }
          });
        }
      });
    },

    handleUpdate(row) {
      // 回显的原数据
      this.purchaseTradePrice = row.purchaseTradePrice;
      this.purchasePrescriptionPrice = row.purchasePrescriptionPrice;
      this.medicinesName = row.medicinesName;

      this.update_resetTemp(); //表单重置
      this.dialogFormVisible2 = true;
      this.$nextTick(() => {
        const id = row.purchaseId || this.purchaseId;
        DzmHisPurchase_update_getid(id).then((response) => {
          this.update_temp = response.data;
          this.title = "修改页面";
          this.$refs["update_from"].clearValidate();
          ReferenceError;
        });
      });
    },

    updateData() {
      // 执行后端 修改方法
      this.$refs["update_from"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.update_temp);
          console.log(Object.assign(this.update_temp));

          DzmHisPurchase_update(tempData).then((res) => {
            if (res.code == 200) {
              this.dialogFormVisible2 = false;
              this.getDoctors();
              this.$notify({
                title: "修改",
                message: "修改成功",
                type: "success",
                duration: 2000,
              });
            }
          });
        }
      });
    },

    //添加  的 model
    drug_module_query() {
      DzmHisMember_list().then((response) => {
        if (response.code === 200) {
          this.drug_query = response.data;
        } else {
          this.$message({
            message: "数据加载错误",
            type: "error",
          });
        }
      });
    },

    //获取id
    clickItemInfo(row) {
      var med = row.medicinesId;
      this.temp.medicinesId = med;
      this.Drug_model = false;
    },

    Numerical_empty() {
      alert(
        "若想批量清空药品数值，点击“清空数值”按钮，会将全部设置好的药品值全部清空"
      );
    },

    Volume_set() {
      alert(
        "勾选要批量设置的药品，点击“批量设置”在批量设置弹框中，对所以勾选的药品进行批量设置，可以批量设置药品数量，批发价格，处方价格"
      );
    },

    //供应商id
    supplier() {
      DzmHisSupplier_list().then((response) => {
        if (response.code === 200) {
          this.supplier_list = response.data;
        }
        console.log(this.supplier_list);
      });
    },
    //直接入库
    Go_inventory() {},

    //提交
    submit_inventory() {
      this.submit_audit.batchesOfInventoryId = this.inventory_numbering;
      //  this.submit_audit.company_id = '1';       诊所ID
      this.submit_audit.supplierId = this.formItem_select;
      console.log(this.submit_audit.supplierId);
      this.submit_audit.batchesOfInventoryNumber = this.inventory_numbering;
      // this.submit_audit.                //采购员ID

      let i = 0;
      let a = 0;
      for (i; i < this.list.length; i++) {
        a = a + this.list[i].purchasePrescriptionTotalAmount;
      }

      this.submit_audit.batchesOfInventoryTotalMoney = a;

      // // this.submit_audit.batchesOfInventoryDate = this.list[0].createTime;
      // if (this.submit_audit.batchesOfInventoryDate == "") {

      //    this.$notify({
      //     message: "请添加数据!",
      //     type: "warning",
      //   });
      //   return this.submit_audit.batchesOfInventoryDate = this.list[0].createTime;

      // } else {

      // }

      this.submit_audit.batchesOfInventoryDate = this.list[0].createTime;

      //判断  供应商  no null
      if (this.submit_audit.supplierId == "") {
        this.$notify({
          message: "请选择供应商!",
          type: "warning",
        });
      } else {
        DzmHisBatchesOfInventory_insert(this.submit_audit).then((res) => {
          if (res.code == 200) {
            this.list = [];
            this.$notify({
              // title: "新增",
              message: "提交成功!",
              type: "success",
              // duration: 2000,
            });
          }
        });
        dzmHisPurchase_update_state(this.submit_audit.batchesOfInventoryId);
      }
    },

    //订单随机
    getProjectNum() {
      const projectTime = new Date(); // 当前中国标准时间
      const Year = projectTime.getFullYear(); // 获取当前年份 支持IE和火狐浏览器.
      const Month = projectTime.getMonth() + 1; // 获取中国区月份
      const Day = projectTime.getDate(); // 获取几号
      var CurrentDate = Year;
      if (Month >= 10) {
        // 判断月份和几号是否大于10或者小于10
        CurrentDate += Month;
      } else {
        CurrentDate += "0" + Month;
      }
      if (Day >= 10) {
        CurrentDate += Day;
      } else {
        CurrentDate += "0" + Day;
      }
      return CurrentDate;
    },
  },
  //获取时间单编号
};
</script>
